package com.woniuxy.sales.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.sales.mapper.AppointmentsMapper;
import com.woniuxy.sales.mapper.CategoriesMapper;
import com.woniuxy.sales.mapper.ProductsMapper;
import com.woniuxy.sales.model.dto.SubmitAppointments;
import com.woniuxy.sales.model.entity.Appointments;
import com.woniuxy.sales.model.entity.Categories;
import com.woniuxy.sales.model.entity.Products;
import com.woniuxy.sales.model.vo.AppointmentsVo;
import com.woniuxy.sales.service.AppointmentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 【预约表】
*/
@Service
public class AppointmentsServiceImpl extends ServiceImpl<AppointmentsMapper, Appointments> implements AppointmentsService{
    @Autowired
    private AppointmentsMapper appointmentsMapper;
    @Autowired
    private ProductsMapper productsMapper;
    @Autowired
    private CategoriesMapper categoriesMapper;


    private static final String key = "appointments";

    @Override
    public List<AppointmentsVo> query(Integer userId) {
        LambdaQueryWrapper<Appointments> wrapper = new LambdaQueryWrapper<>();
        //查询某个用户的所有预约单
        wrapper.eq(Appointments::getUserId, userId);
        //按预约时间倒序排列
        wrapper.orderByDesc(Appointments::getAppointmentDate);
        List<Appointments> appointments = appointmentsMapper.selectList(wrapper);
        List<AppointmentsVo> appointmentsVos = appointments.stream().map(app -> {//每一个收藏的商品
            AppointmentsVo appointmentsVo = BeanUtil.copyProperties(app, AppointmentsVo.class);
            //根据商品id得到商品详情
            Products products = productsMapper.selectById(app.getProductId());
            //由商品id得到类型，从而得到类型名称
            Categories categories = categoriesMapper.selectById(products.getCategoryId());
            appointmentsVo.setCategoryName(categories.getCategoryName());
            BeanUtil.copyProperties(products, appointmentsVo);
            return appointmentsVo;
        }).collect(Collectors.toList());
        return appointmentsVos;
    }
    @Override//查询某个用户：指定状态的预约，如果没有指定状态，则查询所有的预约
    public List<AppointmentsVo> queryByStatus(Integer userId, Integer status) {
        LambdaQueryWrapper<Appointments> wrapper = new LambdaQueryWrapper<>();
        //查询某个用户的所有预约单
        wrapper.eq(Appointments::getUserId, userId);
        //如果不为0，则查询指定状态的订单
        if (status != 0) {
            wrapper.eq(Appointments::getStatus, status);
        }
        //按预约时间倒序排列
        wrapper.orderByDesc(Appointments::getAppointmentDate);
        List<Appointments> appointments = appointmentsMapper.selectList(wrapper);

        //将预约对象，转换为预约vo对象
        List<AppointmentsVo> appointmentsVos = appointments.stream().map(app -> {
            AppointmentsVo appointmentsVo = BeanUtil.copyProperties(app, AppointmentsVo.class);
            // 根据商品id得到商品详情
            Products products = productsMapper.selectById(app.getProductId());
            if (products != null) {
                // 由商品id得到类型，从而得到类型名称
                Categories categories = categoriesMapper.selectById(products.getCategoryId());
                if (categories != null) {
                    appointmentsVo.setCategoryName(categories.getCategoryName());
                }
                BeanUtil.copyProperties(products, appointmentsVo);
            } else {
                // 处理产品不存在的情况
                appointmentsVo.setCategoryName("未知类别");
            }
            return appointmentsVo;
        }).collect(Collectors.toList());

        return appointmentsVos;
    }


    @Override
    public void remove(Integer id) {
        appointmentsMapper.deleteById(id);
    }

    @Override
    public boolean updateStatusToExpired(Long appointmentId) {
        Appointments appointment = appointmentsMapper.selectById(appointmentId);
        if (appointment != null) {
            long diffInMillis = System.currentTimeMillis() - appointment.getAppointmentDate().getTime();
            long diffInDays = TimeUnit.MILLISECONDS.toDays(diffInMillis);
            if (diffInDays > 2 && appointment.getStatus() != 3) {
                appointment.setStatus(3);
                int updateCount = appointmentsMapper.updateById(appointment);
                return updateCount > 0;
            }
        }
        return false;
    }

    @Override
    public void submit(Integer userId, SubmitAppointments params) {
        Appointments appointments = new Appointments();
        appointments.setUserId(userId);
        appointments.setProductId(params.getProductId());
        appointments.setTelephone(params.getTelephone());
        appointments.setAppointmentDate(params.getAppointmentDate());
        appointments.setStatus(1);
        appointments.setSex(params.getSex());
        appointmentsMapper.insert(appointments);
    }
}




